package dao

import (
	"errors"
	"gorm.io/gorm"
	"product-service/common"
	"product-service/dao/entity"
)

var (
	PmsAttrGroupDao = &pmsAttrGroupDao{}
)

type pmsAttrGroupDao struct {
}

func (this *pmsAttrGroupDao) FindAttrGroupsByCateId(db *gorm.DB, id int64) ([]*entity.PmsAttrGroup, error) {
	var attrgroups []*entity.PmsAttrGroup
	err := db.Where("catelog_id=?", id).Find(&attrgroups).Error
	if err != nil {
		return nil, err
	}
	return attrgroups, nil
}

func (this *pmsAttrGroupDao) FindById(db *gorm.DB, id int64) (*entity.PmsAttrGroup, error) {
	model := &entity.PmsAttrGroup{}
	db.Find(model, id)
	if model.CatelogId == 0 {
		return nil, errors.New("无此用户")
	}
	return model, nil
}

type P struct {
	P1 int64 `json:"p1"`
	P2 int64 `json:"p2"`
}

func (this *pmsAttrGroupDao) FindAll(db *gorm.DB, query *common.PageQuery) ([]*entity.PmsAttrGroup, int64, error) {
	tx := db.Scopes(Page(int(query.Page), int(query.Size)))

	var models []*entity.PmsAttrGroup
	model := query.Model.(*entity.PmsAttrGroup)

	//count不包含limit条件
	var count int64
	tx.Model(&model).Count(&count)

	newTx := tx.Where("attr_group_name like ?", "%"+model.AttrGroupName+"%")
	if model.CatelogId == 0 {
		err := newTx.Find(&models).Error
		if err != nil {
			return nil, 0, err
		}
	} else {
		//如果选中了分类,便加上id条件
		err := tx.Where("catelog_id=?", model.CatelogId).Find(&models).Error
		if err != nil {
			return nil, 0, err
		}
	}
	return models, count, nil
}

func (this *pmsAttrGroupDao) DeleteById(db *gorm.DB, id int64) error {
	tx := db.Delete(&entity.PmsAttrGroup{}, id)
	if tx.Error != nil {
		return errors.New("无效删除")
	}
	return nil
}
func (this *pmsAttrGroupDao) UpdateById(db *gorm.DB, id int64, model *entity.PmsAttrGroup) error {
	model.AttrGroupId = id
	tx := db.Updates(model)
	if tx.Error != nil {
		return errors.New("无效更新")
	}
	return nil
}

func (this *pmsAttrGroupDao) Save(db *gorm.DB, model *entity.PmsAttrGroup) (*entity.PmsAttrGroup, error) {
	tx := db.Create(model)
	if tx.RowsAffected == 0 {
		return nil, errors.New("保存失败")
	}
	return model, nil
}
